package org.nyt.medicalstore.service.impl;

import org.nyt.medicalstore.model.Drug;
import org.nyt.medicalstore.model.Symptom;
import org.nyt.medicalstore.repository.DrugRepository;
import org.nyt.medicalstore.repository.SaleRecordRepository;
import org.nyt.medicalstore.repository.SymptomRepository;
import org.nyt.medicalstore.service.DrugSimilarityService;
import org.nyt.medicalstore.service.RecommendationService;
import org.nyt.medicalstore.service.SymptomDrugRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class RecommendationServiceImpl implements RecommendationService {
    @Autowired
    private DrugRepository drugRepository;
    
    @Autowired
    private SaleRecordRepository saleRecordRepository;

    @Autowired
    private SymptomDrugRelationService symptomDrugRelationService;

    @Autowired
    private DrugSimilarityService drugSimilarityService;

    @Autowired
    private SymptomRepository symptomRepository;

    // 症状关键词映射表
    private final Map<String, List<String>> symptomKeywordMap = new HashMap<>();
    
    public RecommendationServiceImpl() {
        // 初始化症状关键词映射
        initializeSymptomKeywords();
    }

    private void initializeSymptomKeywords() {
        // 感冒相关
        symptomKeywordMap.put("感冒", Arrays.asList("感冒", "发热", "咳嗽", "流涕", "头痛"));
        // 消化系统
        symptomKeywordMap.put("消化", Arrays.asList("胃痛", "消化不良", "腹泻", "便秘", "恶心"));
        // 皮肤问题
        symptomKeywordMap.put("皮肤", Arrays.asList("瘙痒", "皮疹", "过敏", "皮炎"));
        // 疼痛
        symptomKeywordMap.put("疼痛", Arrays.asList("头痛", "牙痛", "关节痛", "肌肉痛"));
    }

    @Override
    public List<Drug> recommendBySymptoms(String symptoms) {
        // 1. 提取症状关键词
        List<String> keywords = new ArrayList<>();
        for (Map.Entry<String, List<String>> entry : symptomKeywordMap.entrySet()) {
            if (entry.getValue().stream().anyMatch(symptoms::contains)) {
                keywords.add(entry.getKey());
            }
        }
        
        // 2. 如果没有匹配到关键词，直接使用原始症状搜索
        if (keywords.isEmpty()) {
            return drugRepository.findByDescriptionContaining(symptoms);
        }
        
        // 3. 使用关键词搜索相关药品
        List<Drug> recommendations = new ArrayList<>();
        for (String keyword : keywords) {
            Symptom symptom = symptomRepository.findByName(keyword).orElse(null);
            if (symptom != null) {
                recommendations.addAll(symptomDrugRelationService.getRelatedDrugs(symptom.getId()));
            }
        }
        
        // 4. 去重并返回结果
        return new ArrayList<>(new LinkedHashSet<>(recommendations));
    }

    @Override
    public List<Drug> recommendRelatedDrugs(Long drugId) {
        //获取与当前药品相似度大于0.7的药品
        List<Drug> relatedDrugs = drugSimilarityService.getSimilarDrugs(drugId, 0.7);

        return relatedDrugs;
    }

    @Override
    public List<Drug> recommendByUserHistory(Long userId) {
        List<Drug> recommendDrugs = new ArrayList<>();
        // 获取用户最近购买的药品
        List<Drug> recentDrugs = saleRecordRepository.findRecentDrugsByUserId(userId, 5);
        //根据历史记录获取相关药品
        for (Drug recentDrug: recentDrugs) {
            recommendDrugs.addAll(recommendRelatedDrugs(recentDrug.getId()));
        }
        // 去重并取其中的30个，然后返回结果
        return new ArrayList<>(new LinkedHashSet<>(recommendDrugs)).stream().limit(30).collect(Collectors.toList());
    }

    @Override
    public List<Drug> getPopularRecommendations() {
        // 获取销量最高的药品
        return saleRecordRepository.findTopSellingDrugs(5, 0);
    }
}